package com.run_java_test.test3;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;

@Component
public class DynamicControllerRegistrar {

    private final ApplicationContext applicationContext;

    public DynamicControllerRegistrar(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void registerControllerFromSource(String sourceFilePath) {
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            throw new IllegalArgumentException("Source file does not exist: " + sourceFilePath);
        }

        // 编译 Java 源文件
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            throw new IllegalStateException("Cannot find the system Java compiler. Check that your environment includes a JDK.");
        }

        // 假设编译输出目录是源文件目录的 "bin" 子目录
        File binDir = new File(sourceFile.getParent(), "bin");
        if (!binDir.exists()) {
            binDir.mkdirs();
        }

        // 编译源文件，并指定输出目录
        int compilationResult = compiler.run(null, null, null, "-d", binDir.getAbsolutePath(), sourceFile.getPath());
        if (compilationResult != 0) {
            throw new RuntimeException("Compilation failed for source file: " + sourceFilePath);
        }

        // 加载编译后的类
        try (URLClassLoader classLoader = new URLClassLoader(new URL[]{binDir.toURI().toURL()})) {
            Class<?> controllerClass = classLoader.loadClass("com.run_java_test.test3.DynamicController");

            // 注册 Bean
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(controllerClass);
            beanFactory.registerBeanDefinition(controllerClass.getSimpleName(), builder.getBeanDefinition());

            // 触发 RequestMappingHandlerMapping 的重新初始化
            triggerRequestMappingHandlerMappingReinitialization();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Class not found after compilation: com.run_java_test.test3.DynamicController", e);
        } catch (IOException e) {
            throw new RuntimeException("Error creating URLClassLoader", e);
        }
    }

    private void triggerRequestMappingHandlerMappingReinitialization() {
        // 这种方法可能不是最佳实践，并且可能在不同版本的 Spring 中有所不同
        // 你可能需要找到更适合你的 Spring 版本和配置的方法
        RequestMappingHandlerMapping handlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        handlerMapping.afterPropertiesSet(); // 在某些 Spring 版本中，这可能足以触发重新初始化
        // 或者，你可能需要调用其他方法或重置其他组件
    }
}